import cv2 as cv
import numpy as np
import os
import sys
from PyCmpltrtok.common import sep, get_dir_name_ext, check_np_detailed

XDIR, XNAME, XEXT = get_dir_name_ext(os.path.abspath(__file__))
THE_PIC_PATH = os.path.join(XDIR, 'dog_bird.tmp.jpg')

if '__main__' == __name__:
    image_np = cv.imread(THE_PIC_PATH, cv.IMREAD_COLOR)
    check_np_detailed(image_np, 'image_np')

    image_enc = cv.imencode('.jpg', image_np)[1]
    check_np_detailed(image_enc, 'image_enc')
    image_enc = np.array(image_enc)
    check_np_detailed(image_enc, 'image_enc')
    image_enc_str = image_enc.tostring()
    print('image_enc_str', type(image_enc_str), len(image_enc_str))

    # arr = np.fromstring(image_enc_str, np.uint8)  # DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
    arr = np.frombuffer(image_enc_str, np.uint8)
    check_np_detailed(arr, 'arr')
    image_dec = cv.imdecode(arr, cv.IMREAD_COLOR)
    check_np_detailed(image_dec, 'image_dec')

    cv.imshow('winname', image_dec)
    print('Press any key on the imshow window to continue ...')
    cv.waitKey(0)
